<template>
    <!-- 填写申请单弹框 -->
    <el-dialog ref="checkDialog" v-if="showFlag" class="l-dialog s-lg check-dialog" :title="dialogTitle" :visible.sync="showFlag" append-to-body @close="onClose(false)" :close-on-press-escape="false" :close-on-click-modal="false">
        <el-row class="application-warpper" :gutter="24" v-loading="loading" :element-loading-text="loadingText" element-loading-background="rgba(255,255,255,.7)">
            <el-col :span="12">
                <!-- 搜索 -->
                <!-- <div class="search-bar">
                    <el-input placeholder="请输入项目名称进行添加" v-model.trim="search" maxlength="100" size="small">
                        <template slot="append" type="primary">搜索</template>
                    </el-input>
                </div> -->
                <div class="tabs-box">
                    <el-tabs v-model="activeTabId" @tab-click="toggleClassTabs">
                        <el-tab-pane v-for="(item, idx) in classData" :key="idx" :label="item.checklistClassName" :name="String(item.id)"></el-tab-pane>
                    </el-tabs>
                    <div class="tree-box">
                        <el-tree ref="classTree" :data="classTreeList" v-loading="treeLoading" node-key="id" :props="defaultProps" empty-text="暂无数据" default-expand-all :expand-on-click-node="false">
                            <span class="custom-tree-node" slot-scope="{ node, data }">
                                <span class="label-name">{{ node.label }}</span>
                                <div class="handle-group" v-if="!checkProjectItem.checklistClassName && data.templateValue">
                                    <el-button type="text" size="mini" @click="onAddItem(data)">新增申请单</el-button>
                                </div>
                            </span>
                        </el-tree>
                    </div>
                </div>
                <!-- 项目 -->
                <div class="box detail-box">
                    <div class="box-title">项目</div>
                    <div class="box-inner">
                        <el-tag v-if="checkProjectItem.checklistClassName" class="tag-item" closable type="primary" disable-transitions @close="onDeleteItem(checkProjectItem)">
                            {{checkProjectItem.checklistClassName}}
                        </el-tag>
                    </div>
                </div>
            </el-col>
            <el-col :span="12">
                <div class="box form-box">
                    <h3 class="head-title">检查申请单</h3>
                    <div class="box-title">
                        <span>检查项目：</span>
                        {{checkProjectItem.checklistClassName || ''}}
                    </div>
                    <div class="box-inner">
                        <!-- 模板一 -->
                        <el-form v-if="checkProjectItem.templateValue == 'inquiry_checklist_common_template'" class="l-form form-padding" ref="oneTempForm" :model="oneTempForm" :rules="oneTempFormRule" label-position="left" label-width="165px" size="small">
                            <el-form-item label="上次心电图检查号:" prop="checklistLastCode">
                                <el-input class="u-inp" v-model.trim="oneTempForm.checklistLastCode"></el-input>
                            </el-form-item>
                            <el-form-item label="病例及摘要:" prop="checklistAbstract">
                                <el-input class="u-inp" v-model.trim="oneTempForm.checklistAbstract" maxlength="200"></el-input>
                            </el-form-item>
                            <el-form-item label="【血压】收缩压:" prop="checklistSbp">
                                <el-input-number class="u-inp u-inp-number" v-model.trim="oneTempForm.checklistSbp" :precision="2" :controls="false" :min="0" :max="9999999">
                                    <span slot="suffix" class="u-inp-unit">毫米汞柱</span>
                                </el-input-number>
                            </el-form-item>
                            <el-form-item label="【血压】舒张压:" prop="checklistDbp">
                                <el-input-number class="u-inp u-inp-number" v-model.trim="oneTempForm.checklistDbp" :precision="2" :controls="false" :min="0" :max="9999999">
                                    <span slot="suffix" class="u-inp-unit">毫米汞柱</span>
                                </el-input-number>
                            </el-form-item>
                            <el-form-item label="备注:" prop="remarks">
                                <el-input class="u-inp" type="textarea" :row="2" resize="none" v-model.trim="oneTempForm.remarks"></el-input>
                            </el-form-item>
                            <!-- 洋地黄判断 -->
                            <el-form-item label="最近两周洋地黄用量：" prop="isDigitalization" @change="toggletFormRadio('oneTempForm', 'isDigitalization')">
                                <el-radio v-model="oneTempForm.isDigitalization" label="1">是</el-radio>
                                <el-radio v-model="oneTempForm.isDigitalization" label="0">否</el-radio>
                            </el-form-item>
                            <template v-if="oneTempForm.isDigitalization == '1'">
                                <el-form-item label="开始服用时间：" prop="checklistDigitalizationStart" :rules="[{required: oneTempForm.isDigitalization == '1', message: '洋地黄开始服用时间不能为空', trigger: 'change'}]">
                                    <el-date-picker class="u-inp" size="small" v-model="oneTempForm.checklistDigitalizationStart" type="date" value-format="yyyy-MM-dd" placeholder="洋地黄开始服用时间" @change="val => validateStartToEnd('oneTempForm', 'isDigitalization', val, oneTempForm.checklistDigitalizationEnd)">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="结束服用时间：" prop="checklistDigitalizationEnd" :rules="[{required: oneTempForm.isDigitalization == '1', validator: (rule, value, callback) => validateEndDate(rule, value, callback, 'isDigitalization',oneTempForm.checklistDigitalizationStart), trigger: 'change'}]">
                                    <el-date-picker class="u-inp" size="small" v-model="oneTempForm.checklistDigitalizationEnd" type="date" value-format="yyyy-MM-dd" placeholder="洋地黄结束服用时间" :disabled="!oneTempForm.checklistDigitalizationStart">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="用量:" prop="checklistDigitalizationNum" :rules="[{required: oneTempForm.isDigitalization == '1', message: '洋地黄用量不能为空', trigger: 'blur'}]">
                                    <el-input class="u-inp" v-model.trim="oneTempForm.checklistDigitalizationNum" placeholder="洋地黄用量"></el-input>
                                </el-form-item>
                            </template>

                            <!-- 其他相关药物判断 -->
                            <el-form-item label="其他相关药物：" prop="isOtherDrugs" @change="toggletFormRadio('oneTempForm', 'isOtherDrugs')">
                                <el-radio v-model="oneTempForm.isOtherDrugs" label="1">是</el-radio>
                                <el-radio v-model="oneTempForm.isOtherDrugs" label="0">否</el-radio>
                            </el-form-item>
                            <template v-if="oneTempForm.isOtherDrugs == '1'">
                                <el-form-item label="药品名称:" prop="checklistOtherDrugsName" :rules="[{required: oneTempForm.isOtherDrugs == '1', message: '其他相关药品名称不能为空', trigger: 'blur'}]">
                                    <el-input class="u-inp" v-model.trim="oneTempForm.checklistOtherDrugsName" placeholder="其他相关药品名称"></el-input>
                                </el-form-item>
                                <el-form-item label="开始服用时间：" prop="checklistOtherDrugsStart" :rules="[{required: oneTempForm.isOtherDrugs == '1', message: '其他相关药物开始服用时间不能为空', trigger: 'change'}]">
                                    <el-date-picker class="u-inp" size="small" v-model="oneTempForm.checklistOtherDrugsStart" type="date" value-format="yyyy-MM-dd" placeholder="其他相关药物开始服用时间" @change="val => validateStartToEnd('oneTempForm', 'isOtherDrugs', val, oneTempForm.checklistOtherDrugsEnd)">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="结束服用时间：" prop="checklistOtherDrugsEnd" :rules="[{required: oneTempForm.isOtherDrugs == '1', validator: (rule, value, callback) => validateEndDate(rule, value, callback, 'isOtherDrugs',oneTempForm.checklistOtherDrugsStart), trigger: 'change'}]">
                                    <el-date-picker class="u-inp" size="small" v-model="oneTempForm.checklistOtherDrugsEnd" type="date" value-format="yyyy-MM-dd" placeholder="其他相关药物结束服用时间" :disabled="!oneTempForm.checklistOtherDrugsStart">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="用量:" prop="checklistOtherDrugsNum" :rules="[{required: oneTempForm.isOtherDrugs == '1', message: '其他相关药物用量不能为空', trigger: 'blur'}]">
                                    <el-input class="u-inp" v-model.trim="oneTempForm.checklistOtherDrugsNum" placeholder="其他相关药物用量"></el-input>
                                </el-form-item>
                            </template>
                        </el-form>

                        <!-- 模板二 -->
                        <el-form v-else-if="checkProjectItem.templateValue == 'inquiry_checklist_ecg_template'" class="l-form form-padding" ref="twoTempForm" :model="twoTempForm" label-position="left" label-width="165px" size="small">
                            <el-form-item label="病例及摘要:" prop="checklistAbstract">
                                <el-input class="u-inp" v-model.trim="twoTempForm.checklistAbstract" maxlength="200"></el-input>
                            </el-form-item>
                            <el-form-item label="有关检验结果:" prop="checkResult">
                                <el-input class="u-inp" v-model.trim="twoTempForm.checkResult"></el-input>
                            </el-form-item>
                            <el-form-item label="备注:" prop="remarks">
                                <el-input class="u-inp" type="textarea" :row="2" resize="none" v-model.trim="twoTempForm.remarks"></el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </el-col>
        </el-row>
        <div slot="footer" class="dialog-footer">
            <el-button size="small" class="dialog-btn" @click="onClose(false)">取消</el-button>
            <el-button size="small" type="primary" class="dialog-btn" @click="onSubmitSave">保存</el-button>
        </div>
    </el-dialog>
</template>

<script>
    /* 
申请单模板一：templateValue=inquiry_checklist_common_template（表单字段多）
申请单模板二：templateValue=inquiry_checklist_ecg_template（表单字段多）
*/
    export default {
        name: '',
        data() {
            return {
                logId: '', // 问诊id
                loading: false,
                loadingText: '',
                showFlag: false,
                dialogTitle: '',
                dialogHandle: 'add',
                editId: '', // 编辑id

                tempType: {
                    // 模板一
                    'inquiry_checklist_common_template': {
                        formName: 'oneTempForm',
                        addApi: 'addApplicationTemplateOne',
                        updateApi: 'updateApplicationTemplateOne',
                        detailApi: 'getApplicationTemplateOneDetail'
                    },
                    // 模板二
                    'inquiry_checklist_ecg_template': {
                        formName: 'twoTempForm',
                        addApi: 'addApplicationTemplateTwo',
                        updateApi: 'updateApplicationTemplateTwo',
                        detailApi: 'getApplicationTemplateTwoDetail'
                    },
                },

                search: '', // 搜索
                /* 分类标题选项卡 */
                activeTabId: '1', // 选项卡active
                classData: [], // 检验检查分类标题

                /* 分类数据树形 */
                treeLoading: false,
                classTreeList: [],
                defaultProps: {
                    children: 'list',
                    label: 'checklistClassName',
                },

                /* 添加的项目 */
                checkProjectItem: {}, // 添加的项目

                /* 申请单模板一 */
                oneTempForm: {
                    checklistLastCode: '', // 心电图编号
                    checklistAbstract: '', // 病例及摘要
                    checklistSbp: undefined, // 收缩压
                    checklistDbp: undefined, // 舒张压
                    remarks: '',
                    isDigitalization: '0', //是否使用洋地黄
                    checklistDigitalizationStart: '', //洋地黄开始服用时间
                    checklistDigitalizationEnd: '', //洋地黄结束服用时间
                    checklistDigitalizationNum: '', //洋地黄用量
                    isOtherDrugs: '0', //是否服用其他相关药物
                    checklistOtherDrugsName: '', //其他相关药物名称
                    checklistOtherDrugsStart: '', //其他相关药物开始服用时间
                    checklistOtherDrugsEnd: '', //其他相关药物结束服用时间
                    checklistOtherDrugsNum: '', //其他相关药物用量
                },
                oneTempFormRule: {
                    checklistSbp: [
                        { required: false, validator: this.validateInputNumber, trigger: 'blur' }
                    ],
                    checklistDbp: [
                        { required: false, validator: this.validateInputNumber, trigger: 'blur' }
                    ],
                },

                /* 申请单模板二 */
                twoTempForm: {
                    checkResult: '', // 检验结果	
                    checklistAbstract: '', // 病历及检查摘要			
                    remarks: '',
                },
            }
        },
        methods: {
            // 切换单选框时，清空之前的填写
            toggletFormRadio(formName, key) {
                if (key == 'isDigitalization') {
                    this[formName].checklistDigitalizationStart = '';
                    this[formName].checklistDigitalizationEnd = '';
                    this[formName].checklistDigitalizationNum = '';
                } else {
                    this[formName].checklistOtherDrugsName = '';
                    this[formName].checklistOtherDrugsStart = '';
                    this[formName].checklistOtherDrugsEnd = '';
                    this[formName].checklistOtherDrugsNum = '';
                }
            },
            // 验证表单数字输入
            validateInputNumber(rule, value, callback) {
                if (value || value === 0) {
                    if (value <= 0) {
                        callback('数值必须大于0')
                    } else {
                        callback()
                    }
                } else {
                    callback();
                }
            },
            // 更改开始时间时，重新验证结束时间
            validateStartToEnd(formName, key, startVal, endVal) {
                let tips = key == 'isDigitalization' ? '洋地黄' : '其他药物';
                let endKey = key == 'isDigitalization' ? 'checklistDigitalizationEnd' : 'checklistOtherDrugsEnd';

                if (endVal) {
                    this.$refs[formName].validateField(endKey)
                }
            },
            // 验证结束时间是否大于开始时间
            validateEndDate(rule, value, callback, key, startVal) {
                let tips = key == 'isDigitalization' ? '洋地黄' : '其他药物';
                if (value) {
                    if (new Date(startVal).getTime() > new Date(value).getTime()) {
                        callback(new Error('服用结束时间必须大于服用开始时间'))
                    } else {
                        callback();
                    }
                } else {
                    callback(tips + '服用结束时间不能为空');
                }
            },
            // 添加项目
            onAddItem(data) {
                if (this.checkProjectItem.checklistClassName) return;

                this.checkProjectItem = data;
                // console.log(data)
                this.setFormData(this.tempType[data.templateValue].formName);
            },
            // 移除项目
            onDeleteItem(data, index) {
                this.checkProjectItem = {};

                this.setFormData(this.tempType[data.templateValue].formName);
            },
            /** 打开检验检查弹框
             * @params type 操作类型：add,edit
             * @params logId 问诊id
             * @params id 当前编辑的意见单id，type=edit时必传 
             * */
            onOpen({ type, logId, id, template } = {}) {
                this.showFlag = true;
                this.logId = logId;
                this.dialogHandle = type;
                this.loading = true;
                this.loadingText = '加载中';
                this.checkProjectItem = {};
                this.editId = id || '';

                if (type == 'edit') {
                    this.dialogTitle = '编辑申请单';
                    this.getDetail(template)
                } else {
                    this.dialogTitle = '新增申请单';
                }

                this.getCheckTabs();

                setTimeout(() => {
                    this.loading = false;
                }, 400)
            },
            // 获取申请单详情
            getDetail(template) {
                if (!template) return;

                let oTemp = this.tempType[template];

                this.$ajax[oTemp.detailApi]({ id: this.editId }).then(res => {

                    this.checkProjectItem.id = res.data.checkId || '';
                    this.checkProjectItem.checklistClassName = res.data.checkProject || '';
                    this.checkProjectItem.templateValue = template || '';

                    this.setFormData(oTemp.formName, res.data);
                }).catch(err => {
                    this.$util.message(err.msg);
                })
            },
            setFormData(formName, data = {}) {
                if (!formName) return;
                for (let k in this[formName]) {
                    if (k == 'checklistSbp' || k == 'checklistDbp') {
                        this[formName][k] = data[k] || undefined;
                    } else if (k == 'isDigitalization' || k == 'isOtherDrugs') {
                        this[formName][k] = data[k] || '0'
                    } else {
                        this[formName][k] = data[k] || '';
                    }
                }
            },
            // 切换选项卡
            toggleClassTabs() {
                this.getClassifyList(this.activeTabId);
            },
            // 获取检验检查分类(选项卡展示)
            getCheckTabs() {
                this.$ajax.getChecklistClassName().then(res => {

                    this.classData = res.data.list || [];

                    this.activeTabId = (this.classData[0] && '' + this.classData[0].id) || '0';
                    this.getClassifyList(this.activeTabId);
                }).catch(err => {
                    this.$message.closeAll();
                    this.$message.error(err.msg);

                    this.classData = [];
                })
            },
            // 获取所有分类
            getClassifyList(id) {
                let params = {
                    id: id || 1, // 0，默认查一级节点
                };
                this.treeLoading = true;
                this.$ajax.clickChecklistClass(params).then(res => {
                    let result = [];
                    let arr = res.data.list || [];
                    /* 整理检查分类数据格式 */
                    if (arr.length > 0) {
                        arr.forEach((o1, i1) => {
                            let temp = {
                                id: o1.id,
                                checklistClassName: o1.checklistClassName,
                                list: []
                            }

                            if (o1.list && !Array.isArray(o1.list)) {
                                temp.list = o1.list.list;
                            } else if (o1.list && Array.isArray(o1.list)) {
                                temp.list = o1.list;
                            }

                            result.push(temp);
                        })
                    }

                    this.classTreeList = result;
                    this.treeLoading = false;
                }).catch(err => {
                    this.treeLoading = false;
                    this.$message.closeAll();
                    this.$message.error(err.msg);
                    this.classTreeList = [];
                })
            },
            // 关闭弹框
            onClose(flag) {
                this.showFlag = false;

                this.processingOpinion = ''; // 处理意见
                this.checkProjectArr = []; // 添加的项目

                this.$emit('closed', flag);
            },
            // 保存
            onSubmitSave() {
                this.loading = true;
                this.loadingText = '提交中';

                if (!this.checkProjectItem.checklistClassName) {
                    this.loading = false;
                    this.$message.closeAll();
                    this.$message({
                        type: 'warning',
                        message: '请选择项目'
                    })
                    return;
                }
                let oTemp = this.tempType[this.checkProjectItem.templateValue];
                this.$refs[oTemp.formName].validate(valid => {
                    if (valid) {
                        let params = {
                            checkId: this.checkProjectItem.id,
                            checkProject: this.checkProjectItem.checklistClassName,
                            logId: this.logId,
                        };

                        if (this.dialogHandle == 'edit') {
                            params.id = this.editId;
                        }

                        let apiName = this.dialogHandle == 'edit' ? oTemp.updateApi : oTemp.addApi;

                        if (oTemp.formName == 'twoTempForm') {
                            /* 提交申请单模板二 */
                            for (let k in this[oTemp.formName]) {
                                params[k] = this[oTemp.formName][k] || ''
                            }
                        } else {
                            /* 提交申请单模板一 */
                            for (let k in this[oTemp.formName]) {
                                if (['isDigitalization', 'checklistDigitalizationStart', 'checklistDigitalizationEnd', 'checklistDigitalizationNum'].includes(k)) {
                                    if (this[oTemp.formName][k] == '0') {
                                        params[k] = '0';
                                        params.checklistDigitalizationStart = '';
                                        params.checklistDigitalizationEnd = '';
                                        params.checklistDigitalizationNum = '';
                                    } else {
                                        params[k] = this[oTemp.formName][k];
                                        params.checklistDigitalizationStart = this[oTemp.formName].checklistDigitalizationStart;
                                        params.checklistDigitalizationEnd = this[oTemp.formName].checklistDigitalizationEnd;
                                        params.checklistDigitalizationNum = this[oTemp.formName].checklistDigitalizationNum;

                                        console.log(this[oTemp.formName].checklistDigitalizationStart, params)

                                    }
                                } else if (['isOtherDrugs', 'checklistOtherDrugsName', 'checklistOtherDrugsStart', 'checklistOtherDrugsEnd', 'checklistOtherDrugsNum'].includes(k)) {
                                    if (this[oTemp.formName][k] == '0') {
                                        params[k] = '0';
                                        params.checklistOtherDrugsName = '';
                                        params.checklistOtherDrugsStart = '';
                                        params.checklistOtherDrugsEnd = '';
                                        params.checklistOtherDrugsNum = '';
                                    } else {
                                        params[k] = this[oTemp.formName][k];
                                        params.checklistOtherDrugsName = this[oTemp.formName]['checklistOtherDrugsName'];
                                        params.checklistOtherDrugsStart = this[oTemp.formName]['checklistOtherDrugsStart'];
                                        params.checklistOtherDrugsEnd = this[oTemp.formName]['checklistOtherDrugsEnd'];
                                        params.checklistOtherDrugsNum = this[oTemp.formName]['checklistOtherDrugsNum'];
                                    }
                                } else {
                                    params[k] = this[oTemp.formName][k] || ''
                                }
                            }

                        }

                        this.$ajax[apiName](params).then(res => {
                            this.loading = false;
                            this.$message.closeAll();
                            this.$message({
                                type: 'success',
                                message: res.msg
                            });

                            this.onClose(true)
                        }).catch(err => {
                            this.loading = false;

                            this.$message.closeAll();
                            this.$message({
                                type: 'error',
                                message: err.msg
                            });
                        })
                    } else {
                        this.loading = false;
                    }
                })
            }
        },
        mounted() {

        }
    }
</script>

<style lang="scss" src="./checkDialogStyle.scss"></style>